﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using GroupChat2013.Common;

namespace GroupChat2013.Data
{
    /// <summary>
    /// 数据库存储基类
    /// </summary>
    public abstract class BaseRepository
    {
        /// <summary>
        /// 程序运行目录
        /// </summary>
        private readonly string basePath = AppDomain.CurrentDomain.BaseDirectory;

        /// <summary>
        /// 数据库名称
        /// </summary>
        private const string DBName = "ChatDB.db";

        /// <summary>
        /// 连接串格式
        /// </summary>
        private const string connectionFormat = "Data Source={0};Pooling=True;FailIfMissing=false";

        /// <summary>
        /// 数据库路径
        /// </summary>
        protected string DBPath;

        /// <summary>
        /// 表名称
        /// </summary>
        protected string TableName { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public BaseRepository(string tableName)
            : this(null, tableName)
        {

        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public BaseRepository(string dbPath, string tableName)
        {
            //检测数据库
            DBPath = string.Format(connectionFormat, CheckDB(dbPath));
            TableName = tableName;

            //如果表不存在 则创建
            if (!CheckTable())
            {
                CreateTable();
            }
        }

        /// <summary>
        /// 检测数据库是否存在
        /// </summary>
        private string CheckDB(string dataBasePath)
        {
            string dbPath = string.Empty;
            if (string.IsNullOrEmpty(dataBasePath))
                dbPath = Path.Combine(basePath, "Data");
            else
                dbPath = dataBasePath;

            Tools.CreateDir(dbPath);
            string dbFile = Path.Combine(dbPath, DBName);

            return dbFile;
        }

        /// <summary>
        /// 检测表
        /// </summary>
        protected virtual bool CheckTable()
        {
            string cmdText = "SELECT COUNT(*) FROM sqlite_master where type='table' and name='" + TableName + "';";
            object data = SQLiteHelper.ExecuteScalar(DBPath, cmdText);
            return Convert.ToInt32(data) > 0;
        }

        /// <summary>
        /// 创建表
        /// </summary>
        protected abstract void CreateTable();
    }
}
